package com.dxy.df.core.shiro;

import com.dxy.df.core.exception.BizException;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.util.CollectionUtils;

import java.util.Map;

/**
 * @author ws
 * @Description:
 * @date 2018/3/15 下午1:32
 */
public class DefaultModularRealm extends ModularRealmAuthenticator {

    private Map<String, Object> definedRealms;

    public DefaultModularRealm() {
    }

    /**
     * 调用单个realm执行操作
     */
    @Override
    protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {

        // 如果该realms不支持(不能验证)当前token
        if (!realm.supports(token)) {
            throw new BizException("token错误!");
        }
        AuthenticationInfo info = realm.getAuthenticationInfo(token);
        if (info == null) {
            throw new BizException("token不存在!");
        }
        return info;
    }

    /**
     * 判断登录类型执行操作
     */
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) {
        this.assertRealmsConfigured();
        Realm realm;
        if (authenticationToken instanceof LoginToken) {
            realm = (Realm) this.definedRealms.get("loginRealm");
        } else {
            realm = (Realm) this.definedRealms.get("shiroCasRealm");
        }
        return this.doSingleRealmAuthentication(realm, authenticationToken);
    }

    /**
     * 判断realm是否为空
     */
    @Override
    protected void assertRealmsConfigured() {
        this.definedRealms = this.getDefinedRealms();
        if (CollectionUtils.isEmpty(this.definedRealms)) {
            throw new ShiroException("值传递错误!");
        }
    }

    public Map<String, Object> getDefinedRealms() {
        return this.definedRealms;
    }

    public void setDefinedRealms(Map<String, Object> definedRealms) {
        this.definedRealms = definedRealms;
    }


}
